package com.controller;

import com.controller.vo.ResultVO;
import com.entity.User;
import com.mapper.AccountMapper;
import com.service.UserInfoService;
import com.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.entity.Account;
import com.service.AccountService;

import java.util.HashMap;
import java.util.Map;


/**
 * ClassName: AccountController
 * Description:
 *
 * @Author L_Z_R
 * @Create 2025/05/08 20:25
 * @Version 1.0
 */
@RestController
public class AccountController extends BaseController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private UserInfoService userInfoService;


    @PostMapping("/register")
    public ResultVO<Account> register(@RequestBody Account account) {
        try {
            accountService.insertAccount(account);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return success();
    }

    @PostMapping("/login")
    public ResultVO<Map<String, Object>> login(@RequestBody Account account) {
        //把前端传过来的密码换成MD5加密后的密码,在放进数据库进行查询
        String password = DigestUtils.md5DigestAsHex(account.getPasswordHash().getBytes());

        account = accountService.selectAccountByUsername(account.getUsername(), password);

        // 生成JWT Token（使用用户ID作为subject）
        String token = JwtUtils.generateToken(account.getAccountId().toString());

        //返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("account", account);
        data.put("token", token);
        data.put("expires_in", JwtUtils.EXPIRATION / 1000); // 秒数
        return success(data);
    }

    @GetMapping("getNewAccountCount")
    public ResultVO<Integer> getNewAccountCount() {
        int count = accountService.getNewAccountCount();
        return success(count);
    }

    @GetMapping("getAccountCount")
    public ResultVO<Integer> getAccountCount() {
        int count = accountService.getAccountCount();
        return success(count);
    }
}
